package com.woshua.cameramodel;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

/*
* 相机拍照回调
* */
public class CameraPictureCallback implements Camera.PictureCallback {

    private Context context;

    public CameraPictureCallback(Context context) {
        this.context=context;
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Log.i("yao", "onPictureTaken");
            Toast.makeText(context, "正在保存……", Toast.LENGTH_LONG).show();
            //用BitmapFactory.decodeByteArray()方法可以把相机传回的裸数据转换成Bitmap对象
            //准备一个Bitmap对象
            Bitmap mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            String savePath=Environment.getExternalStorageDirectory().getPath()+ File.separator +
                    new DateFormat().format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            //接下来的工作就是把Bitmap保存成一个存储卡中的文件
            File file = new File(savePath);
            try {
                file.createNewFile();
                BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));
                mBitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
                Toast.makeText(context, "图片保存完毕，在存储卡的根目录"+savePath, Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
